package com.xuecheng.media.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.MediaDto;
import com.xuecheng.commons.model.dto.MediaQueryDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.VodUploadDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mappers.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-24
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate template;

    //获取阿里云上传凭证
    @Override
    public ResponseResult createToken(VodUploadDto dto) throws Exception {
        //1.判断数据是否为空
        String title = dto.getTitle();
        String fileName = dto.getFileName();
        if (ObjectUtil.isEmpty(title) || ObjectUtil.isEmpty(fileName)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }

        //2.获取上传凭证
        CreateUploadVideoResponse uploadVideo = template.createUploadVideo(title, fileName);

        //封装上传凭证
        VodUploadVo vodUploadVo = new VodUploadVo();
        vodUploadVo.setRequestId(uploadVideo.getRequestId());
        vodUploadVo.setUploadAddress(uploadVideo.getUploadAddress());
        vodUploadVo.setVideoId(uploadVideo.getVideoId());
        vodUploadVo.setUploadAuth(uploadVideo.getUploadAuth());
        vodUploadVo.setUserId(AuthInfoHolder.getUserId().toString());

        return ResponseResult.okResult(vodUploadVo);
    }

    //刷新阿里云上传凭证
    @Override
    public ResponseResult refreshToken(String videoId) throws Exception {
        //刷新凭证
        RefreshUploadVideoResponse response = template.refreshUploadVideo(videoId);

        //封装上传凭证
        VodUploadVo vodUploadVo = new VodUploadVo();
        vodUploadVo.setRequestId(response.getRequestId());
        vodUploadVo.setUploadAddress(response.getUploadAddress());
        vodUploadVo.setVideoId(response.getVideoId());
        vodUploadVo.setUploadAuth(response.getUploadAuth());
        vodUploadVo.setUserId(AuthInfoHolder.getUserId().toString());

        //返回数据
        return ResponseResult.okResult(vodUploadVo);
    }

    //保存媒资信息
    @Override
    public ResponseResult saveMedia(MediaDto dto) throws Exception {
        Media media = BeanHelper.copyProperties(dto, Media.class);

        //1.设置基础信息
        AuthInfo authInfo = AuthInfoHolder.getAuthInfo();
        media.setCompanyId(authInfo.getCompanyId());
        media.setCompanyName(authInfo.getCompanyName());
        media.setUsername(authInfo.getUid().toString());
        media.setCreateDate(new Date());
        media.setChangeDate(new Date());
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS);

        //2.设置阿里云参数
        GetPlayInfoResponse response = template.getPlayInfo(dto.getFileId());
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo playInfo = playInfoList.get(0);

        media.setTimelength(playInfo.getDuration());
        media.setUrl(playInfo.getPlayURL());

        boolean b = this.save(media);
        if (!b) {
            throw new BusinessException(ErrorCode.ERROR);
        }

        //保存成功，返回
        return ResponseResult.okResult();
    }

    //分页查询媒资信息
    @Override
    public ResponseResult findMediaList(PageRequest page, MediaQueryDto dto) {
        //设置查询条件
        Page<Media> pageParam = new Page<>(page.getPageNo(), page.getPageSize());
        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(dto.getFilename())) {
            qw.like(Media::getFilename, "%" + dto.getFilename() + "%");
        }
        if (!StringUtils.isEmpty(dto.getType())) {
            qw.eq(Media::getType, dto.getType());
        }
        if (!StringUtils.isEmpty(dto.getAuditStatus())) {
            qw.eq(Media::getAuditStatus, dto.getAuditStatus());
        }

        //设置查询删除状态
        qw.eq(Media::getStatus, CommonConstants.USING_FLAG);

        //构造返回值
        IPage<Media> pageList = this.page(pageParam, qw);
        List<Media> records = pageList.getRecords();
        List<MediaVo> mediaVos = BeanHelper.copyWithCollection(records, MediaVo.class);

        return PageResponseResult.okResult(pageList.getTotal(), mediaVos);
    }

    //根据媒资id获取播放连接
    @Override
    public ResponseResult findPreviewMediaId(String mediaId) throws Exception {
        if (StringUtils.isEmpty(mediaId)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }

        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();
        qw.eq(Media::getStatus, CommonConstants.USING_FLAG);
        qw.eq(Media::getId, mediaId);

        Media param = this.getOne(qw);

        if (param == null) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }

        return ResponseResult.okResult(param.getUrl());
    }

    @Override
    public ResponseResult deleteMedia(String mediaId) throws Exception {
        if (StringUtils.isEmpty(mediaId)) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }

        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();
        qw.eq(Media::getStatus, CommonConstants.USING_FLAG);
        qw.eq(Media::getId, mediaId);

        Media param = this.getOne(qw);

        boolean b = this.removeById(mediaId);
        if (!b) {
            throw new BusinessException(ErrorCode.ERROR);
        }

        template.deleteVideo(param.getFileId());

        return ResponseResult.okResult();
    }


}
